package com.yvon.maple.service.msg.core.support.action;

import cn.hutool.core.collection.CollUtil;
import com.yvon.boot.common.result.ResponseData;
import com.yvon.boot.common.result.ResultCode;
import com.yvon.maple.service.msg.core.model.vo.MessageVo;
import com.yvon.maple.service.msg.core.common.model.send.SendTaskModel;
import com.yvon.maple.service.msg.core.support.pipeline.BusinessProcess;
import com.yvon.maple.service.msg.core.support.pipeline.ProcessContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 前置参数校验
 * 主要功能是：过滤掉消息模板或参数为空的消息、过滤掉消息接收人为空的消息
 *
 * @author : Yvon
 * @since : 2021-12-22
 */
@Slf4j
@Service
public class PreParamCheckAction implements BusinessProcess {

    @Override
    public void process(ProcessContext context) {
        // 存储责任链上下文数据的模型
        SendTaskModel sendTaskModel = (SendTaskModel) context.getProcessModel();

        // 消息模板ID
        Long messageTemplateId = sendTaskModel.getMessageTemplateId();
        // 消息参数
        List<MessageVo> messageVoList = sendTaskModel.getMessageVoList();

        // 没有传入 消息模板Id 或者 messageParam
        if (messageTemplateId == null || CollUtil.isEmpty(messageVoList)) {
            context.setNeedBreak(true).setResponse(ResponseData.failed(ResultCode.CLIENT_BAD_PARAMETERS));
            return;
        }

        // 过滤 receiver=null 的messageParam
        List<MessageVo> resultMessageVoList = messageVoList.stream()
                .filter(messageParam -> CollUtil.isNotEmpty(messageParam.getReceiver()))
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(resultMessageVoList)) {
            context.setNeedBreak(true).setResponse(ResponseData.failed(ResultCode.CLIENT_BAD_PARAMETERS));
            return;
        }

        sendTaskModel.setMessageVoList(resultMessageVoList);

    }
}
